package com.mzj.saas.mservice.house.service;

import com.alibaba.fastjson.JSON;
import com.mzj.saas.commons.DateUtils;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.SQLUtils;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.config.oss.OssConfig;
import com.mzj.saas.mservice.house.entity.Check;
import com.mzj.saas.mservice.house.entity.CheckFile;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.entity.HouseMatchUser;
import com.mzj.saas.mservice.house.repository.CheckFileRepository;
import com.mzj.saas.mservice.house.repository.CheckRepository;
import com.mzj.saas.mservice.house.repository.HouseMatchUserRepository;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.mservice.house.vo.CheckVO;
import com.mzj.saas.mservice.oss.service.OSSService;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CheckService {
    private static final Logger log = LoggerFactory.getLogger(CheckService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private CheckRepository checkRepository;
    @Autowired
    private HouseMatchUserRepository houseMatchUserRepository;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private CheckFileRepository checkFileRepository;
    @Autowired
    private OSSService ossService;
    @Autowired
    private OssConfig ossConfig;
    @Autowired
    private HouseRepository houseRepository;

    public ResultBean<List<AppUser>> findMatchUser(String accessToken, String houseId) {

        try {
            if (StringUtils.isBlank(houseId)) {
                return ResultBean.failedResultOfParamWithMsg("公租房id为空");
            }

            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }

            List<HouseMatchUser> matchUsers = houseMatchUserRepository.findHouseIdAndStatus(houseId, 1);
            if (matchUsers.isEmpty()) {
                log.error("findMatchUser---> [houseId={}]未查到配租记录", houseId);
                return ResultBean.failedResultWithMsg("未查到配租记录");
            }

            List<String> userIds = matchUsers.stream().map(u -> u.getMatchUserId()).collect(Collectors.toList());
            String sql = "SELECT * FROM saas_app_user u WHERE u.id IN "+SQLUtils.foreachIn(userIds.size())+" or u.enterprise_user_id IN " + SQLUtils.foreachIn(userIds.size());
            userIds.addAll(userIds);
            List<AppUser> scaleList = jdbcTemplate.query(sql,
            		new BeanPropertyRowMapper<>(AppUser.class), userIds.toArray());
            if(scaleList.isEmpty()){
            	log.error("findMatchUser---> [userId={}]承租人不存在, userIds={}", JSON.toJSONString(userIds));
                return ResultBean.failedResultOfParamWithMsg("承租人不存在");
            }

            return ResultBean.successfulResult(scaleList);
        } catch (Exception e) {
            log.error("CheckService findMatchUser Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<List<CheckVO>> checkList(String houseId) {
        try {
            if (StringUtils.isBlank(houseId)) {
                return ResultBean.failedResultOfParamWithMsg("公租房id为空");
            }

            List<Check> list = checkRepository.findByHouseId(houseId);
            List<CheckVO> listvo = new ArrayList<>();
            for (Check check : list) {
                CheckVO checkVO = new CheckVO();
                checkVO.setId(check.getId());
                checkVO.setHouseId(check.getHouseId());
                checkVO.setMatchUserId(check.getMatchUserId());
                checkVO.setCheckUserId(check.getCheckUserId());
                checkVO.setCheckType(check.getCheckType());
                checkVO.setCustomTypeName(check.getCustomTypeName());
                checkVO.setContent(check.getContent());
                checkVO.setAuditResult(check.getAuditResult());
                checkVO.setAuditTime(DateUtils.format(check.getAuditTime(), DateUtils.FORMAT_DATETIME_14));
                listvo.add(checkVO);
            }

            // 查询核查用户名称
            List<String> ids = listvo.stream().filter(vo -> vo.getCheckUserId() != null).map(CheckVO::getCheckUserId).distinct().collect(Collectors.toList());
            if (!ids.isEmpty()) {
                List<AppUser> appUsers = appUserRepository.findByIdOrEnterpriseIn(ids, ids);
                for (AppUser appUser : appUsers) {
                    for (CheckVO vo : listvo) {
                        if (vo.getCheckUserId().equals(appUser.getId()) || vo.getCheckUserId().equals(appUser.getEnterpriseUserId())) {
                            vo.setName(appUser.getName());
                        }
                    }
                }
            }

            return ResultBean.successfulResult(listvo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<List<CheckVO>> checkList2(String houseId) {
        try {
            if (StringUtils.isBlank(houseId)) {
                return ResultBean.failedResultOfParamWithMsg("公租房id为空");
            }

            List<Check> list = checkRepository.findByHouseId(houseId);
            List<CheckVO> listvo = new ArrayList<>();
            for (Check check : list) {
                CheckVO checkVO = new CheckVO();
                checkVO.setId(check.getId());
                checkVO.setHouseId(check.getHouseId());
                checkVO.setMatchUserId(check.getMatchUserId());
                checkVO.setCheckUserId(check.getCheckUserId());
                checkVO.setCheckType(check.getCheckType());
                checkVO.setCustomTypeName(check.getCustomTypeName());
                checkVO.setContent(check.getContent());
                checkVO.setAuditResult(check.getAuditResult());
                checkVO.setAuditTime(DateUtils.format(check.getAuditTime(), DateUtils.FORMAT_DATETIME_14));
                listvo.add(checkVO);
            }

            // 查询核查用户名称
            List<String> ids = listvo.stream().filter(vo -> vo.getCheckUserId() != null).map(CheckVO::getCheckUserId)
                    .distinct().collect(Collectors.toList());
            if (!ids.isEmpty()) {
                Map<String, String> map = appUserRepository.findByIdOrEnterpriseIn(ids, ids).stream()
                        .collect(Collectors.toMap(AppUser::getId, AppUser::getName));
                if (!map.isEmpty()) {
                    listvo.forEach(vo -> vo.setName(map.get(vo.getCheckUserId())));
                }
            }

            return ResultBean.successfulResult(listvo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Map<String, Object>> findCheck(Long id) {
        try {
            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("资格核查id为空");
            }

            Optional<Check> optional = checkRepository.findById(id);
            if (!optional.isPresent()) {
                return ResultBean.failedResultWithMsg("资格核查不存在");
            }
            Check check = optional.get();

            Map<String, Object> map = new HashMap<>();
            map.put("checkType", check.getCheckType());
            map.put("customTypeName", check.getCustomTypeName());
            map.put("content", check.getContent());
            map.put("auditResult", check.getAuditResult());
            List<String> url = checkFileRepository.findByCheckId(check.getId()).stream().map(CheckFile::getUrl).collect(Collectors.toList());
            map.put("url", url);

            return ResultBean.successfulResult(map);
        } catch (Exception e) {
            log.error("CheckService findCheck Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> saveCheck(String accessToken, CheckVO vo) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            String houseId = vo.getHouseId();
            String matchUserId = vo.getMatchUserId();

            if (StringUtils.isBlank(houseId)) {
                return ResultBean.failedResultOfParamWithMsg("公租房id为空");
            }
            if (StringUtils.isBlank(matchUserId)) {
                return ResultBean.failedResultOfParamWithMsg("承租人id为空");
            }
            if (vo.getCheckType() == null) {
                return ResultBean.failedResultOfParamWithMsg("核查类型为空");
            }
            if (vo.getCheckType() == 9 && StringUtils.isBlank(vo.getCustomTypeName())) {
                return ResultBean.failedResultOfParamWithMsg("自定义类型名称为空");
            }
            if (StringUtils.isBlank(vo.getContent())) {
                return ResultBean.failedResultOfParamWithMsg("核查内容为空");
            }
            if (vo.getAuditResult() == null) {
                return ResultBean.failedResultOfParamWithMsg("核查结果为空");
            }
            if (vo.getUrls() == null || vo.getUrls().size() == 0) {
                return ResultBean.failedResultOfParamWithMsg("文件路径为空");
            }

            Check check = new Check();
            check.setHouseId(houseId);
            check.setMatchUserId(matchUserId);
            check.setCheckUserId(userId);
            check.setCheckType(vo.getCheckType());
            if (vo.getCheckType() == 9) {
                check.setCustomTypeName(vo.getCustomTypeName());
            }
            check.setContent(vo.getContent());
            check.setAuditResult(vo.getAuditResult());
            check.setAuditTime(new Date());
            Check save = checkRepository.save(check);

            /*for (MultipartFile file : files) {
                // 文件上传
                ResultBean<Object> objectResultBean = ossService.putFile(ossConfig.getOssBucketName(), file, OSSUploadFileTypeEnum.PROVE.toString());
                String fileKey = objectResultBean.getResultData().toString();
                String url = ossService.getOssFilePath(fileKey);
                // 新增核查文件表数据
                CheckFile checkFile = new CheckFile();
                checkFile.setCheckId(save.getId());
                checkFile.setUrl(url);
                checkFileRepository.save(checkFile);
            }*/

            for (String url : vo.getUrls()) {
                // 新增核查文件表数据
                CheckFile checkFile = new CheckFile();
                checkFile.setCheckId(save.getId());
                checkFile.setUrl(url);
                checkFileRepository.save(checkFile);
            }

            // 公租房状态改成已核查
            Optional<House> optional = houseRepository.findById(houseId);
            if (!optional.isPresent()) {
                return ResultBean.failedResultWithMsg("公租房不存在");
            }
            House house = optional.get();
            house.setCheckStatus(1);
            houseRepository.save(house);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("CheckService saveCheck Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

}
